package de.firefligher.network.ice.messenger.client;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Event;
import java.awt.Font;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

import javax.swing.JFrame;


public class ChatClient extends JFrame implements Runnable {
	private static final long serialVersionUID = 6677192193646474313L;
	private Socket socket;
	private DataInputStream input;
	private PrintStream output;
	private Thread thread;
	private TextField inputfield;
	private TextArea outputarea;
	
	public static void main(String[] args) {
		new ChatClient();
	}
	
	public ChatClient() {
		inputfield = new TextField();
		
		outputarea = new TextArea();
		outputarea.setFont(new Font("Dialog", Font.PLAIN, 12));
		outputarea.setEditable(false);
		
		this.setLayout(new BorderLayout());
		this.add("South", inputfield);
		this.add("Center", outputarea);
		this.setBackground(Color.BLACK);
		inputfield.setBackground(Color.WHITE);
		outputarea.setBackground(Color.WHITE);
		
		try {
			socket = new Socket("localhost", 4048);
			input = new DataInputStream(socket.getInputStream());
			output = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			System.out.println("Connection to server failed!");
			System.exit(1);
		}
		
		say("Connected to server...");
		
		if(thread == null) {
			thread = new Thread(this);
			thread.setPriority(Thread.MIN_PRIORITY);
			thread.start();
		}
		
		this.addWindowListener(new WindowAdapter() {
			@SuppressWarnings("deprecation")
			@Override
			public void windowClosing(WindowEvent e) {
				try {
					socket.close();
				} catch (IOException e1) { }
				
				if((thread != null) && thread.isAlive()) {
					thread.stop();
					thread = null;
				}
				System.exit(0);
			}
		});
		
		this.setVisible(true);
	}
	
	private void say(String string) {
		outputarea.append("*** " + string + " ***\n");
	}

	@SuppressWarnings("deprecation")
	@Override
	public void run() {
		String line = null;
		
		while(true) {
			try {
				line = input.readLine();
			} catch (IOException e) {
				say("Connection canceled!");
			}
			if(line != null)
				outputarea.append(line + '\n');
		}
	}
	
	@Override
	public boolean action(Event e, Object what) {
		if(e.target == inputfield) {
			String inp = (String)e.arg;
			output.println(inp);
			inputfield.setText("");
			return true;
		}
		return false;
	}
}
